package com.young.common.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 跨域处理过滤器
 * Created by rookie on 2018/4/16.
 */
public class CrossDomainFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(CrossDomainFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("[跨域请求过滤器] 初始化完成!");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ((HttpServletResponse)response).setHeader("Access-Control-Allow-Origin", "*");
        ((HttpServletResponse)response).setHeader("Access-Control-Allow-Headers", "Authentication");
        ((HttpServletResponse)response).setHeader("Access-Control-Allow-Methods",
                "POST, GET, OPTIONS, DELETE");
        ((HttpServletResponse)response).addHeader(
                "Access-Control-Allow-Headers",
                "Origin, No-Cache, X-Requested-With,"
                        + " If-Modified-Since, Pragma, Last-Modified, Cache-Control,"
                        + " Expires, Content-Type, X-E4M-With");
        ((HttpServletResponse)response).setHeader("Access-Control-Allow-Credentials", "true"); // 是否支持cookie跨域
        logger.debug("[跨域请求过滤器] 完成跨域处理!");
        chain.doFilter(request, response);//通过,继续执行过滤链
    }

    @Override
    public void destroy() {
        logger.info("[跨域请求过滤器] 销毁完成!");
    }
}
